<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Classes &middot; Crafting Interpreters</title>

<!-- Tell mobile browsers we're optimized for them and they don't need to crop
     the viewport. -->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="style.css" />

<!-- Oh, God, Source Code Pro is so beautiful it makes me want to cry. -->
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400|Source+Sans+Pro:300,400,600' rel='stylesheet' type='text/css'>

<link rel="icon" type="image/png" href="image/favicon.png" />
<script src="jquery-3.4.1.min.js"></script>
<script src="script.js"></script>

<!-- Google analytics -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-42804721-2', 'auto');
  ga('send', 'pageview');
</script>

</head>
<body id="top">

<!-- <div class="scrim"></div> -->
<nav class="wide">
  <a href="/"><img src="image/logotype.png" title="Crafting Interpreters"></a>
  <div class="contents">
<h3><a href="#top">Classes<small>12</small></a></h3>

<ul>
    <li><a href="#oop-and-classes"><small>12.1</small> OOP and Classes</a></li>
    <li><a href="#class-declarations"><small>12.2</small> Class Declarations</a></li>
    <li><a href="#creating-instances"><small>12.3</small> Creating Instances</a></li>
    <li><a href="#properties-on-instances"><small>12.4</small> Properties on Instances</a></li>
    <li><a href="#methods-on-classes"><small>12.5</small> Methods on Classes</a></li>
    <li><a href="#this"><small>12.6</small> This</a></li>
    <li><a href="#constructors-and-initializers"><small>12.7</small> Constructors and Initializers</a></li>
    <li class="divider"></li>
    <li class="end-part"><a href="#challenges">Challenges</a></li>
    <li class="end-part"><a href="#design-note"><small>note</small>Prototypes and Power</a></li>
</ul>


<div class="prev-next">
    <a href="resolving-and-binding.html" title="Resolving and Binding" class="left">&larr;&nbsp;Previous</a>
    <a href="a-tree-walk-interpreter.html" title="A Tree-Walk Interpreter">&uarr;&nbsp;Up</a>
    <a href="inheritance.html" title="Inheritance" class="right">Next&nbsp;&rarr;</a>
</div>  </div>
</nav>

<nav class="narrow">
<a href="/"><img src="image/logotype.png" title="Crafting Interpreters"></a>
<a href="resolving-and-binding.html" title="Resolving and Binding" class="prev">←</a>
<a href="inheritance.html" title="Inheritance" class="next">→</a>
</nav>

<div class="page">
<div class="nav-wrapper">
<nav class="floating">
  <a href="/"><img src="image/logotype.png" title="Crafting Interpreters"></a>
  <div class="expandable">
<h3><a href="#top">Classes<small>12</small></a></h3>

<ul>
    <li><a href="#oop-and-classes"><small>12.1</small> OOP and Classes</a></li>
    <li><a href="#class-declarations"><small>12.2</small> Class Declarations</a></li>
    <li><a href="#creating-instances"><small>12.3</small> Creating Instances</a></li>
    <li><a href="#properties-on-instances"><small>12.4</small> Properties on Instances</a></li>
    <li><a href="#methods-on-classes"><small>12.5</small> Methods on Classes</a></li>
    <li><a href="#this"><small>12.6</small> This</a></li>
    <li><a href="#constructors-and-initializers"><small>12.7</small> Constructors and Initializers</a></li>
    <li class="divider"></li>
    <li class="end-part"><a href="#challenges">Challenges</a></li>
    <li class="end-part"><a href="#design-note"><small>note</small>Prototypes and Power</a></li>
</ul>


<div class="prev-next">
    <a href="resolving-and-binding.html" title="Resolving and Binding" class="left">&larr;&nbsp;Previous</a>
    <a href="a-tree-walk-interpreter.html" title="A Tree-Walk Interpreter">&uarr;&nbsp;Up</a>
    <a href="inheritance.html" title="Inheritance" class="right">Next&nbsp;&rarr;</a>
</div>  </div>
  <a id="expand-nav">≡</a>
</nav>
</div>

<article class="chapter">

  <div class="number">12</div>
  <h1>Classes</h1>

<blockquote>
<p>One has no right to love or hate anything if one has not acquired a thorough
knowledge of its nature. Great love springs from great knowledge of the
beloved object, and if you know it but little you will be able to love it only
a little or not at all.</p>
<p><cite>Leonardo da Vinci</cite></p>
</blockquote>
<p>We&rsquo;re eleven chapters in, and the interpreter sitting on your machine is nearly
a complete scripting language. It could use a couple of built-in data structures
like lists and maps, and it certainly needs a core library for file I/O, user
input, etc. But the language itself is sufficient. We&rsquo;ve got a little procedural
language in the same vein as BASIC, Tcl, Scheme (minus macros), and early
versions of Python and Lua.</p>
<p>If this were the &rsquo;80s, we&rsquo;d stop here. But today, many popular languages support
&ldquo;object-oriented programming&rdquo;. Adding that to Lox will give users a familiar set
of tools for writing larger programs. Even if you personally don&rsquo;t <span
name="hate">like</span> OOP, this chapter and <a href="inheritance.html">the next</a> will help
you understand how others design and build object systems.</p>
<aside name="hate">
<p>If you <em>really</em> hate classes, though, you can skip these two chapters. They are
fairly isolated from the rest of the book. Personally, I find it&rsquo;s good to learn
more about the things I dislike. Things look simple at a distance, but as I get
closer, details emerge and I gain a more nuanced perspective.</p>
</aside>
<h2><a href="#oop-and-classes" id="oop-and-classes"><small>12&#8202;.&#8202;1</small>OOP and Classes</a></h2>
<p>There are three broad paths to object-oriented programming: classes,
<a href="http://gameprogrammingpatterns.com/prototype.html">prototypes</a>, and <span name="multimethods"><a href="https://en.wikipedia.org/wiki/Multiple_dispatch">multimethods</a></span>. Classes
came first and are the most popular style. With the rise of JavaScript (and to a
lesser extent <a href="https://www.lua.org/pil/13.4.1.html">Lua</a>), prototypes are more widely known than they used to be.
I&rsquo;ll talk more about those <a href="#design-note">later</a>. For Lox, we&rsquo;re taking the, ahem, classic
approach.</p>
<aside name="multimethods">
<p>Multimethods are the approach you&rsquo;re least likely to be familiar with. I&rsquo;d love
to talk more about them<span class="em">&mdash;</span>I designed <a href="http://magpie-lang.org/">a hobby language</a> around them
once and they are <em>super rad</em><span class="em">&mdash;</span>but there are only so many pages I can fit in.
If you&rsquo;d like to learn more, take a look at <a href="https://en.wikipedia.org/wiki/Common_Lisp_Object_System">CLOS</a> (the object system in
Common Lisp), <a href="https://opendylan.org/">Dylan</a>, <a href="https://julialang.org/">Julia</a>, or <a href="https://docs.raku.org/language/functions#Multi-dispatch">Raku</a>.</p>
</aside>
<p>Since you&rsquo;ve written about a thousand lines of Java code with me already, I&rsquo;m
assuming you don&rsquo;t need a detailed introduction to object orientation. The main
goal is to bundle data with the code that acts on it. Users do that by declaring
a <em>class</em> that:</p>
<p><span name="circle"></span></p>
<ol>
<li>
<p>Exposes a <em>constructor</em> to create and initialize new <em>instances</em> of the
class</p>
</li>
<li>
<p>Provides a way to store and access <em>fields</em> on instances</p>
</li>
<li>
<p>Defines a set of <em>methods</em> shared by all instances of the class that
operate on each instances&rsquo; state.</p>
</li>
</ol>
<p>That&rsquo;s about as minimal as it gets. Most object-oriented languages, all the way
back to Simula, also do inheritance to reuse behavior across classes. We&rsquo;ll add
that in the <a href="inheritance.html">next chapter</a>. Even kicking that out, we still have a
lot to get through. This is a big chapter and everything doesn&rsquo;t quite come
together until we have all of the above pieces, so gather your stamina.</p>
<aside name="circle"><img src="image/classes/circle.png" alt="The relationships between classes, methods, instances, constructors, and fields." />
<p>It&rsquo;s like the circle of life, <em>sans</em> Sir Elton John.</p>
</aside>
<h2><a href="#class-declarations" id="class-declarations"><small>12&#8202;.&#8202;2</small>Class Declarations</a></h2>
<p>Like we do, we&rsquo;re gonna start with syntax. A <code>class</code> statement introduces a new
name, so it lives in the <code>declaration</code> grammar rule.</p>
<div class="codehilite"><pre><span class="i">declaration</span>    → <span class="i">classDecl</span>
               | <span class="i">funDecl</span>
               | <span class="i">varDecl</span>
               | <span class="i">statement</span> ;

<span class="i">classDecl</span>      → <span class="s">&quot;class&quot;</span> <span class="t">IDENTIFIER</span> <span class="s">&quot;{&quot;</span> <span class="i">function</span>* <span class="s">&quot;}&quot;</span> ;
</pre></div>
<p>The new <code>classDecl</code> rule relies on the <code>function</code> rule we defined
<a href="functions.html#function-declarations">earlier</a>. To refresh your memory:</p>
<div class="codehilite"><pre><span class="i">function</span>       → <span class="t">IDENTIFIER</span> <span class="s">&quot;(&quot;</span> <span class="i">parameters</span>? <span class="s">&quot;)&quot;</span> <span class="i">block</span> ;
<span class="i">parameters</span>     → <span class="t">IDENTIFIER</span> ( <span class="s">&quot;,&quot;</span> <span class="t">IDENTIFIER</span> )* ;
</pre></div>
<p>In plain English, a class declaration is the <code>class</code> keyword, followed by the
class&rsquo;s name, then a curly-braced body. Inside that body is a list of method
declarations. Unlike function declarations, methods don&rsquo;t have a leading <span
name="fun"><code>fun</code></span> keyword. Each method is a name, parameter list, and
body. Here&rsquo;s an example:</p>
<aside name="fun">
<p>Not that I&rsquo;m trying to say methods aren&rsquo;t fun or anything.</p>
</aside>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Breakfast</span> {
  <span class="i">cook</span>() {
    <span class="k">print</span> <span class="s">&quot;Eggs a-fryin&#39;!&quot;</span>;
  }

  <span class="i">serve</span>(<span class="i">who</span>) {
    <span class="k">print</span> <span class="s">&quot;Enjoy your breakfast, &quot;</span> + <span class="i">who</span> + <span class="s">&quot;.&quot;</span>;
  }
}
</pre></div>
<p>Like most dynamically typed languages, fields are not explicitly listed in the
class declaration. Instances are loose bags of data and you can freely add
fields to them as you see fit using normal imperative code.</p>
<p>Over in our AST generator, the <code>classDecl</code> grammar rule gets its own statement
<span name="class-ast">node</span>.</p>
<div class="codehilite"><pre class="insert-before">      &quot;Block      : List&lt;Stmt&gt; statements&quot;,
</pre><div class="source-file"><em>tool/GenerateAst.java</em><br>
in <em>main</em>()</div>
<pre class="insert">      <span class="s">&quot;Class      : Token name, List&lt;Stmt.Function&gt; methods&quot;</span>,
</pre><pre class="insert-after">      &quot;Expression : Expr expression&quot;,
</pre></div>
<div class="source-file-narrow"><em>tool/GenerateAst.java</em>, in <em>main</em>()</div>

<aside name="class-ast">
<p>The generated code for the new node is in <a href="appendix-ii.html#class-statement">Appendix II</a>.</p>
</aside>
<p>It stores the class&rsquo;s name and the methods inside its body. Methods are
represented by the existing Stmt.Function class that we use for function
declaration AST nodes. That gives us all the bits of state that we need for a
method: name, parameter list, and body.</p>
<p>A class can appear anywhere a named declaration is allowed, triggered by the
leading <code>class</code> keyword.</p>
<div class="codehilite"><pre class="insert-before">    try {
</pre><div class="source-file"><em>lox/Parser.java</em><br>
in <em>declaration</em>()</div>
<pre class="insert">      <span class="k">if</span> (<span class="i">match</span>(<span class="i">CLASS</span>)) <span class="k">return</span> <span class="i">classDeclaration</span>();
</pre><pre class="insert-after">      if (match(FUN)) return function(&quot;function&quot;);
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, in <em>declaration</em>()</div>

<p>That calls out to:</p>
<div class="codehilite"><div class="source-file"><em>lox/Parser.java</em><br>
add after <em>declaration</em>()</div>
<pre>  <span class="k">private</span> <span class="t">Stmt</span> <span class="i">classDeclaration</span>() {
    <span class="t">Token</span> <span class="i">name</span> = <span class="i">consume</span>(<span class="i">IDENTIFIER</span>, <span class="s">&quot;Expect class name.&quot;</span>);
    <span class="i">consume</span>(<span class="i">LEFT_BRACE</span>, <span class="s">&quot;Expect &#39;{&#39; before class body.&quot;</span>);

    <span class="t">List</span>&lt;<span class="t">Stmt</span>.<span class="t">Function</span>&gt; <span class="i">methods</span> = <span class="k">new</span> <span class="t">ArrayList</span>&lt;&gt;();
    <span class="k">while</span> (!<span class="i">check</span>(<span class="i">RIGHT_BRACE</span>) &amp;&amp; !<span class="i">isAtEnd</span>()) {
      <span class="i">methods</span>.<span class="i">add</span>(<span class="i">function</span>(<span class="s">&quot;method&quot;</span>));
    }

    <span class="i">consume</span>(<span class="i">RIGHT_BRACE</span>, <span class="s">&quot;Expect &#39;}&#39; after class body.&quot;</span>);

    <span class="k">return</span> <span class="k">new</span> <span class="t">Stmt</span>.<span class="t">Class</span>(<span class="i">name</span>, <span class="i">methods</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, add after <em>declaration</em>()</div>

<p>There&rsquo;s more meat to this than most of the other parsing methods, but it roughly
follows the grammar. We&rsquo;ve already consumed the <code>class</code> keyword, so we look for
the expected class name next, followed by the opening curly brace. Once inside
the body, we keep parsing method declarations until we hit the closing brace.
Each method declaration is parsed by a call to <code>function()</code>, which we defined
back in the <a href="functions.html">chapter where functions were introduced</a>.</p>
<p>Like we do in any open-ended loop in the parser, we also check for hitting the
end of the file. That won&rsquo;t happen in correct code since a class should have a
closing brace at the end, but it ensures the parser doesn&rsquo;t get stuck in an
infinite loop if the user has a syntax error and forgets to correctly end the
class body.</p>
<p>We wrap the name and list of methods into a Stmt.Class node and we&rsquo;re done.
Previously, we would jump straight into the interpreter, but now we need to
plumb the node through the resolver first.</p>
<div class="codehilite"><div class="source-file"><em>lox/Resolver.java</em><br>
add after <em>visitBlockStmt</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Void</span> <span class="i">visitClassStmt</span>(<span class="t">Stmt</span>.<span class="t">Class</span> <span class="i">stmt</span>) {
    <span class="i">declare</span>(<span class="i">stmt</span>.<span class="i">name</span>);
    <span class="i">define</span>(<span class="i">stmt</span>.<span class="i">name</span>);
    <span class="k">return</span> <span class="k">null</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, add after <em>visitBlockStmt</em>()</div>

<p>We aren&rsquo;t going to worry about resolving the methods themselves yet, so for now
all we need to do is declare the class using its name. It&rsquo;s not common to
declare a class as a local variable, but Lox permits it, so we need to handle it
correctly.</p>
<p>Now we interpret the class declaration.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitBlockStmt</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Void</span> <span class="i">visitClassStmt</span>(<span class="t">Stmt</span>.<span class="t">Class</span> <span class="i">stmt</span>) {
    <span class="i">environment</span>.<span class="i">define</span>(<span class="i">stmt</span>.<span class="i">name</span>.<span class="i">lexeme</span>, <span class="k">null</span>);
    <span class="t">LoxClass</span> <span class="i">klass</span> = <span class="k">new</span> <span class="t">LoxClass</span>(<span class="i">stmt</span>.<span class="i">name</span>.<span class="i">lexeme</span>);
    <span class="i">environment</span>.<span class="i">assign</span>(<span class="i">stmt</span>.<span class="i">name</span>, <span class="i">klass</span>);
    <span class="k">return</span> <span class="k">null</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitBlockStmt</em>()</div>

<p>This looks similar to how we execute function declarations. We declare the
class&rsquo;s name in the current environment. Then we turn the class <em>syntax node</em>
into a LoxClass, the <em>runtime</em> representation of a class. We circle back and
store the class object in the variable we previously declared. That two-stage
variable binding process allows references to the class inside its own methods.</p>
<p>We will refine it throughout the chapter, but the first draft of LoxClass looks
like this:</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxClass.java</em><br>
create new file</div>
<pre><span class="k">package</span> <span class="i">com.craftinginterpreters.lox</span>;

<span class="k">import</span> <span class="i">java.util.List</span>;
<span class="k">import</span> <span class="i">java.util.Map</span>;

<span class="k">class</span> <span class="t">LoxClass</span> {
  <span class="k">final</span> <span class="t">String</span> <span class="i">name</span>;

  <span class="t">LoxClass</span>(<span class="t">String</span> <span class="i">name</span>) {
    <span class="k">this</span>.<span class="i">name</span> = <span class="i">name</span>;
  }

  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">String</span> <span class="i">toString</span>() {
    <span class="k">return</span> <span class="i">name</span>;
  }
}
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, create new file</div>

<p>Literally a wrapper around a name. We don&rsquo;t even store the methods yet. Not
super useful, but it does have a <code>toString()</code> method so we can write a trivial
script and test that class objects are actually being parsed and executed.</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">DevonshireCream</span> {
  <span class="i">serveOn</span>() {
    <span class="k">return</span> <span class="s">&quot;Scones&quot;</span>;
  }
}

<span class="k">print</span> <span class="t">DevonshireCream</span>; <span class="c">// Prints &quot;DevonshireCream&quot;.</span>
</pre></div>
<h2><a href="#creating-instances" id="creating-instances"><small>12&#8202;.&#8202;3</small>Creating Instances</a></h2>
<p>We have classes, but they don&rsquo;t do anything yet. Lox doesn&rsquo;t have &ldquo;static&rdquo;
methods that you can call right on the class itself, so without actual
instances, classes are useless. Thus instances are the next step.</p>
<p>While some syntax and semantics are fairly standard across OOP languages, the
way you create new instances isn&rsquo;t. Ruby, following Smalltalk, creates instances
by calling a method on the class object itself, a <span
name="turtles">recursively</span> graceful approach. Some, like C++ and Java,
have a <code>new</code> keyword dedicated to birthing a new object. Python has you &ldquo;call&rdquo;
the class itself like a function. (JavaScript, ever weird, sort of does both.)</p>
<aside name="turtles">
<p>In Smalltalk, even <em>classes</em> are created by calling methods on an existing
object, usually the desired superclass. It&rsquo;s sort of a turtles-all-the-way-down
thing. It ultimately bottoms out on a few magical classes like Object and
Metaclass that the runtime conjures into being <em>ex nihilo</em>.</p>
</aside>
<p>I took a minimal approach with Lox. We already have class objects, and we
already have function calls, so we&rsquo;ll use call expressions on class objects to
create new instances. It&rsquo;s as if a class is a factory function that generates
instances of itself. This feels elegant to me, and also spares us the need to
introduce syntax like <code>new</code>. Therefore, we can skip past the front end straight
into the runtime.</p>
<p>Right now, if you try this:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Bagel</span> {}
<span class="t">Bagel</span>();
</pre></div>
<p>You get a runtime error. <code>visitCallExpr()</code> checks to see if the called object
implements <code>LoxCallable</code> and reports an error since LoxClass doesn&rsquo;t. Not <em>yet</em>,
that is.</p>
<div class="codehilite"><pre class="insert-before">import java.util.Map;

</pre><div class="source-file"><em>lox/LoxClass.java</em><br>
replace 1 line</div>
<pre class="insert"><span class="k">class</span> <span class="t">LoxClass</span> <span class="k">implements</span> <span class="t">LoxCallable</span> {
</pre><pre class="insert-after">  final String name;
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, replace 1 line</div>

<p>Implementing that interface requires two methods.</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxClass.java</em><br>
add after <em>toString</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Object</span> <span class="i">call</span>(<span class="t">Interpreter</span> <span class="i">interpreter</span>,
                     <span class="t">List</span>&lt;<span class="t">Object</span>&gt; <span class="i">arguments</span>) {
    <span class="t">LoxInstance</span> <span class="i">instance</span> = <span class="k">new</span> <span class="t">LoxInstance</span>(<span class="k">this</span>);
    <span class="k">return</span> <span class="i">instance</span>;
  }

  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">int</span> <span class="i">arity</span>() {
    <span class="k">return</span> <span class="n">0</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, add after <em>toString</em>()</div>

<p>The interesting one is <code>call()</code>. When you &ldquo;call&rdquo; a class, it instantiates a new
LoxInstance for the called class and returns it. The <code>arity()</code> method is how the
interpreter validates that you passed the right number of arguments to a
callable. For now, we&rsquo;ll say you can&rsquo;t pass any. When we get to user-defined
constructors, we&rsquo;ll revisit this.</p>
<p>That leads us to LoxInstance, the runtime representation of an instance of a Lox
class. Again, our first implementation starts small.</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxInstance.java</em><br>
create new file</div>
<pre><span class="k">package</span> <span class="i">com.craftinginterpreters.lox</span>;

<span class="k">import</span> <span class="i">java.util.HashMap</span>;
<span class="k">import</span> <span class="i">java.util.Map</span>;

<span class="k">class</span> <span class="t">LoxInstance</span> {
  <span class="k">private</span> <span class="t">LoxClass</span> <span class="i">klass</span>;

  <span class="t">LoxInstance</span>(<span class="t">LoxClass</span> <span class="i">klass</span>) {
    <span class="k">this</span>.<span class="i">klass</span> = <span class="i">klass</span>;
  }

  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">String</span> <span class="i">toString</span>() {
    <span class="k">return</span> <span class="i">klass</span>.<span class="i">name</span> + <span class="s">&quot; instance&quot;</span>;
  }
}
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, create new file</div>

<p>Like LoxClass, it&rsquo;s pretty bare bones, but we&rsquo;re only getting started. If you
want to give it a try, here&rsquo;s a script to run:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Bagel</span> {}
<span class="k">var</span> <span class="i">bagel</span> = <span class="t">Bagel</span>();
<span class="k">print</span> <span class="i">bagel</span>; <span class="c">// Prints &quot;Bagel instance&quot;.</span>
</pre></div>
<p>This program doesn&rsquo;t do much, but it&rsquo;s starting to do <em>something</em>.</p>
<h2><a href="#properties-on-instances" id="properties-on-instances"><small>12&#8202;.&#8202;4</small>Properties on Instances</a></h2>
<p>We have instances, so we should make them useful. We&rsquo;re at a fork in the road.
We could add behavior first<span class="em">&mdash;</span>methods<span class="em">&mdash;</span>or we could start with state<span class="em">&mdash;</span>properties. We&rsquo;re going to take the latter because, as we&rsquo;ll see, the two get
entangled in an interesting way and it will be easier to make sense of them if
we get properties working first.</p>
<p>Lox follows JavaScript and Python in how it handles state. Every instance is an
open collection of named values. Methods on the instance&rsquo;s class can access and
modify properties, but so can <span name="outside">outside</span> code.
Properties are accessed using a <code>.</code> syntax.</p>
<aside name="outside">
<p>Allowing code outside of the class to directly modify an object&rsquo;s fields goes
against the object-oriented credo that a class <em>encapsulates</em> state. Some
languages take a more principled stance. In Smalltalk, fields are accessed using
simple identifiers<span class="em">&mdash;</span>essentially, variables that are only in scope inside a
class&rsquo;s methods. Ruby uses <code>@</code> followed by a name to access a field in an
object. That syntax is only meaningful inside a method and always accesses state
on the current object.</p>
<p>Lox, for better or worse, isn&rsquo;t quite so pious about its OOP faith.</p>
</aside>
<div class="codehilite"><pre><span class="i">someObject</span>.<span class="i">someProperty</span>
</pre></div>
<p>An expression followed by <code>.</code> and an identifier reads the property with that
name from the object the expression evaluates to. That dot has the same
precedence as the parentheses in a function call expression, so we slot it into
the grammar by replacing the existing <code>call</code> rule with:</p>
<div class="codehilite"><pre><span class="i">call</span>           → <span class="i">primary</span> ( <span class="s">&quot;(&quot;</span> <span class="i">arguments</span>? <span class="s">&quot;)&quot;</span> | <span class="s">&quot;.&quot;</span> <span class="t">IDENTIFIER</span> )* ;
</pre></div>
<p>After a primary expression, we allow a series of any mixture of parenthesized
calls and dotted property accesses. &ldquo;Property access&rdquo; is a mouthful, so from
here on out, we&rsquo;ll call these &ldquo;get expressions&rdquo;.</p>
<h3><a href="#get-expressions" id="get-expressions"><small>12&#8202;.&#8202;4&#8202;.&#8202;1</small>Get expressions</a></h3>
<p>The <span name="get-ast">syntax tree node</span> is:</p>
<div class="codehilite"><pre class="insert-before">      &quot;Call     : Expr callee, Token paren, List&lt;Expr&gt; arguments&quot;,
</pre><div class="source-file"><em>tool/GenerateAst.java</em><br>
in <em>main</em>()</div>
<pre class="insert">      <span class="s">&quot;Get      : Expr object, Token name&quot;</span>,
</pre><pre class="insert-after">      &quot;Grouping : Expr expression&quot;,
</pre></div>
<div class="source-file-narrow"><em>tool/GenerateAst.java</em>, in <em>main</em>()</div>

<aside name="get-ast">
<p>The generated code for the new node is in <a href="appendix-ii.html#get-expression">Appendix II</a>.</p>
</aside>
<p>Following the grammar, the new parsing code goes in our existing <code>call()</code>
method.</p>
<div class="codehilite"><pre class="insert-before">    while (true) {<span name="while-true"> </span>
      if (match(LEFT_PAREN)) {
        expr = finishCall(expr);
</pre><div class="source-file"><em>lox/Parser.java</em><br>
in <em>call</em>()</div>
<pre class="insert">      } <span class="k">else</span> <span class="k">if</span> (<span class="i">match</span>(<span class="i">DOT</span>)) {
        <span class="t">Token</span> <span class="i">name</span> = <span class="i">consume</span>(<span class="i">IDENTIFIER</span>,
            <span class="s">&quot;Expect property name after &#39;.&#39;.&quot;</span>);
        <span class="i">expr</span> = <span class="k">new</span> <span class="t">Expr</span>.<span class="t">Get</span>(<span class="i">expr</span>, <span class="i">name</span>);
</pre><pre class="insert-after">      } else {
        break;
      }
    }
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, in <em>call</em>()</div>

<p>The outer <code>while</code> loop there corresponds to the <code>*</code> in the grammar rule. We zip
along the tokens building up a chain of calls and gets as we find parentheses
and dots, like so:</p><img src="image/classes/zip.png" alt="Parsing a series of '.' and '()' expressions to an AST." />
<p>Instances of the new Expr.Get node feed into the resolver.</p>
<div class="codehilite"><div class="source-file"><em>lox/Resolver.java</em><br>
add after <em>visitCallExpr</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Void</span> <span class="i">visitGetExpr</span>(<span class="t">Expr</span>.<span class="t">Get</span> <span class="i">expr</span>) {
    <span class="i">resolve</span>(<span class="i">expr</span>.<span class="i">object</span>);
    <span class="k">return</span> <span class="k">null</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, add after <em>visitCallExpr</em>()</div>

<p>OK, not much to that. Since properties are looked up <span
name="dispatch">dynamically</span>, they don&rsquo;t get resolved. During resolution,
we recurse only into the expression to the left of the dot. The actual property
access happens in the interpreter.</p>
<aside name="dispatch">
<p>You can literally see that property dispatch in Lox is dynamic since we don&rsquo;t
process the property name during the static resolution pass.</p>
</aside>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitCallExpr</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Object</span> <span class="i">visitGetExpr</span>(<span class="t">Expr</span>.<span class="t">Get</span> <span class="i">expr</span>) {
    <span class="t">Object</span> <span class="i">object</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">object</span>);
    <span class="k">if</span> (<span class="i">object</span> <span class="k">instanceof</span> <span class="t">LoxInstance</span>) {
      <span class="k">return</span> ((<span class="t">LoxInstance</span>) <span class="i">object</span>).<span class="i">get</span>(<span class="i">expr</span>.<span class="i">name</span>);
    }

    <span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">expr</span>.<span class="i">name</span>,
        <span class="s">&quot;Only instances have properties.&quot;</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitCallExpr</em>()</div>

<p>First, we evaluate the expression whose property is being accessed. In Lox, only
instances of classes have properties. If the object is some other type like a
number, invoking a getter on it is a runtime error.</p>
<p>If the object is a LoxInstance, then we ask it to look up the property. It must
be time to give LoxInstance some actual state. A map will do fine.</p>
<div class="codehilite"><pre class="insert-before">  private LoxClass klass;
</pre><div class="source-file"><em>lox/LoxInstance.java</em><br>
in class <em>LoxInstance</em></div>
<pre class="insert">  <span class="k">private</span> <span class="k">final</span> <span class="t">Map</span>&lt;<span class="t">String</span>, <span class="t">Object</span>&gt; <span class="i">fields</span> = <span class="k">new</span> <span class="t">HashMap</span>&lt;&gt;();
</pre><pre class="insert-after">

  LoxInstance(LoxClass klass) {
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, in class <em>LoxInstance</em></div>

<p>Each key in the map is a property name and the corresponding value is the
property&rsquo;s value. To look up a property on an instance:</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxInstance.java</em><br>
add after <em>LoxInstance</em>()</div>
<pre>  <span class="t">Object</span> <span class="i">get</span>(<span class="t">Token</span> <span class="i">name</span>) {
    <span class="k">if</span> (<span class="i">fields</span>.<span class="i">containsKey</span>(<span class="i">name</span>.<span class="i">lexeme</span>)) {
      <span class="k">return</span> <span class="i">fields</span>.<span class="i">get</span>(<span class="i">name</span>.<span class="i">lexeme</span>);
    }

    <span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">name</span>,<span name="hidden"> </span>
        <span class="s">&quot;Undefined property &#39;&quot;</span> + <span class="i">name</span>.<span class="i">lexeme</span> + <span class="s">&quot;&#39;.&quot;</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, add after <em>LoxInstance</em>()</div>

<aside name="hidden">
<p>Doing a hash table lookup for every field access is fast enough for many
language implementations, but not ideal. High performance VMs for languages like
JavaScript use sophisticated optimizations like &ldquo;<a href="http://richardartoul.github.io/jekyll/update/2015/04/26/hidden-classes.html">hidden classes</a>&rdquo; to avoid
that overhead.</p>
<p>Paradoxically, many of the optimizations invented to make dynamic languages fast
rest on the observation that<span class="em">&mdash;</span>even in those languages<span class="em">&mdash;</span>most code is fairly
static in terms of the types of objects it works with and their fields.</p>
</aside>
<p>An interesting edge case we need to handle is what happens if the instance
doesn&rsquo;t <em>have</em> a property with the given name. We could silently return some
dummy value like <code>nil</code>, but my experience with languages like JavaScript is that
this behavior masks bugs more often than it does anything useful. Instead, we&rsquo;ll
make it a runtime error.</p>
<p>So the first thing we do is see if the instance actually has a field with the
given name. Only then do we return it. Otherwise, we raise an error.</p>
<p>Note how I switched from talking about &ldquo;properties&rdquo; to &ldquo;fields&rdquo;. There is a
subtle difference between the two. Fields are named bits of state stored
directly in an instance. Properties are the named, uh, <em>things</em>, that a get
expression may return. Every field is a property, but as we&rsquo;ll see <span
name="foreshadowing">later</span>, not every property is a field.</p>
<aside name="foreshadowing">
<p>Ooh, foreshadowing. Spooky!</p>
</aside>
<p>In theory, we can now read properties on objects. But since there&rsquo;s no way to
actually stuff any state into an instance, there are no fields to access. Before
we can test out reading, we must support writing.</p>
<h3><a href="#set-expressions" id="set-expressions"><small>12&#8202;.&#8202;4&#8202;.&#8202;2</small>Set expressions</a></h3>
<p>Setters use the same syntax as getters, except they appear on the left side of
an assignment.</p>
<div class="codehilite"><pre><span class="i">someObject</span>.<span class="i">someProperty</span> = <span class="i">value</span>;
</pre></div>
<p>In grammar land, we extend the rule for assignment to allow dotted identifiers
on the left-hand side.</p>
<div class="codehilite"><pre><span class="i">assignment</span>     → ( <span class="i">call</span> <span class="s">&quot;.&quot;</span> )? <span class="t">IDENTIFIER</span> <span class="s">&quot;=&quot;</span> <span class="i">assignment</span>
               | <span class="i">logic_or</span> ;
</pre></div>
<p>Unlike getters, setters don&rsquo;t chain. However, the reference to <code>call</code> allows any
high-precedence expression before the last dot, including any number of
<em>getters</em>, as in:</p><img src="image/classes/setter.png" alt="breakfast.omelette.filling.meat = ham" />
<p>Note here that only the <em>last</em> part, the <code>.meat</code> is the <em>setter</em>. The
<code>.omelette</code> and <code>.filling</code> parts are both <em>get</em> expressions.</p>
<p>Just as we have two separate AST nodes for variable access and variable
assignment, we need a <span name="set-ast">second setter node</span> to
complement our getter node.</p>
<div class="codehilite"><pre class="insert-before">      &quot;Logical  : Expr left, Token operator, Expr right&quot;,
</pre><div class="source-file"><em>tool/GenerateAst.java</em><br>
in <em>main</em>()</div>
<pre class="insert">      <span class="s">&quot;Set      : Expr object, Token name, Expr value&quot;</span>,
</pre><pre class="insert-after">      &quot;Unary    : Token operator, Expr right&quot;,
</pre></div>
<div class="source-file-narrow"><em>tool/GenerateAst.java</em>, in <em>main</em>()</div>

<aside name="set-ast">
<p>The generated code for the new node is in <a href="appendix-ii.html#set-expression">Appendix II</a>.</p>
</aside>
<p>In case you don&rsquo;t remember, the way we handle assignment in the parser is a
little funny. We can&rsquo;t easily tell that a series of tokens is the left-hand side
of an assignment until we reach the <code>=</code>. Now that our assignment grammar rule
has <code>call</code> on the left side, which can expand to arbitrarily large expressions,
that final <code>=</code> may be many tokens away from the point where we need to know
we&rsquo;re parsing an assignment.</p>
<p>Instead, the trick we do is parse the left-hand side as a normal expression.
Then, when we stumble onto the equal sign after it, we take the expression we
already parsed and transform it into the correct syntax tree node for the
assignment.</p>
<p>We add another clause to that transformation to handle turning an Expr.Get
expression on the left into the corresponding Expr.Set.</p>
<div class="codehilite"><pre class="insert-before">        return new Expr.Assign(name, value);
</pre><div class="source-file"><em>lox/Parser.java</em><br>
in <em>assignment</em>()</div>
<pre class="insert">      } <span class="k">else</span> <span class="k">if</span> (<span class="i">expr</span> <span class="k">instanceof</span> <span class="t">Expr</span>.<span class="t">Get</span>) {
        <span class="t">Expr</span>.<span class="t">Get</span> <span class="i">get</span> = (<span class="t">Expr</span>.<span class="t">Get</span>)<span class="i">expr</span>;
        <span class="k">return</span> <span class="k">new</span> <span class="t">Expr</span>.<span class="t">Set</span>(<span class="i">get</span>.<span class="i">object</span>, <span class="i">get</span>.<span class="i">name</span>, <span class="i">value</span>);
</pre><pre class="insert-after">      }
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, in <em>assignment</em>()</div>

<p>That&rsquo;s parsing our syntax. We push that node through into the resolver.</p>
<div class="codehilite"><div class="source-file"><em>lox/Resolver.java</em><br>
add after <em>visitLogicalExpr</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Void</span> <span class="i">visitSetExpr</span>(<span class="t">Expr</span>.<span class="t">Set</span> <span class="i">expr</span>) {
    <span class="i">resolve</span>(<span class="i">expr</span>.<span class="i">value</span>);
    <span class="i">resolve</span>(<span class="i">expr</span>.<span class="i">object</span>);
    <span class="k">return</span> <span class="k">null</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, add after <em>visitLogicalExpr</em>()</div>

<p>Again, like Expr.Get, the property itself is dynamically evaluated, so there&rsquo;s
nothing to resolve there. All we need to do is recurse into the two
subexpressions of Expr.Set, the object whose property is being set, and the
value it&rsquo;s being set to.</p>
<p>That leads us to the interpreter.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitLogicalExpr</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Object</span> <span class="i">visitSetExpr</span>(<span class="t">Expr</span>.<span class="t">Set</span> <span class="i">expr</span>) {
    <span class="t">Object</span> <span class="i">object</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">object</span>);

    <span class="k">if</span> (!(<span class="i">object</span> <span class="k">instanceof</span> <span class="t">LoxInstance</span>)) {<span name="order"> </span>
      <span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">expr</span>.<span class="i">name</span>,
                             <span class="s">&quot;Only instances have fields.&quot;</span>);
    }

    <span class="t">Object</span> <span class="i">value</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">value</span>);
    ((<span class="t">LoxInstance</span>)<span class="i">object</span>).<span class="i">set</span>(<span class="i">expr</span>.<span class="i">name</span>, <span class="i">value</span>);
    <span class="k">return</span> <span class="i">value</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitLogicalExpr</em>()</div>

<p>We evaluate the object whose property is being set and check to see if it&rsquo;s a
LoxInstance. If not, that&rsquo;s a runtime error. Otherwise, we evaluate the value
being set and store it on the instance. That relies on a new method in
LoxInstance.</p>
<aside name="order">
<p>This is another semantic edge case. There are three distinct operations:</p>
<ol>
<li>
<p>Evaluate the object.</p>
</li>
<li>
<p>Raise a runtime error if it&rsquo;s not an instance of a class.</p>
</li>
<li>
<p>Evaluate the value.</p>
</li>
</ol>
<p>The order that those are performed in could be user visible, which means we need
to carefully specify it and ensure our implementations do these in the same
order.</p>
</aside>
<div class="codehilite"><div class="source-file"><em>lox/LoxInstance.java</em><br>
add after <em>get</em>()</div>
<pre>  <span class="t">void</span> <span class="i">set</span>(<span class="t">Token</span> <span class="i">name</span>, <span class="t">Object</span> <span class="i">value</span>) {
    <span class="i">fields</span>.<span class="i">put</span>(<span class="i">name</span>.<span class="i">lexeme</span>, <span class="i">value</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, add after <em>get</em>()</div>

<p>No real magic here. We stuff the values straight into the Java map where fields
live. Since Lox allows freely creating new fields on instances, there&rsquo;s no need
to see if the key is already present.</p>
<h2><a href="#methods-on-classes" id="methods-on-classes"><small>12&#8202;.&#8202;5</small>Methods on Classes</a></h2>
<p>You can create instances of classes and stuff data into them, but the class
itself doesn&rsquo;t really <em>do</em> anything. Instances are just maps and all instances
are more or less the same. To make them feel like instances <em>of classes</em>, we
need behavior<span class="em">&mdash;</span>methods.</p>
<p>Our helpful parser already parses method declarations, so we&rsquo;re good there. We
also don&rsquo;t need to add any new parser support for method <em>calls</em>. We already
have <code>.</code> (getters) and <code>()</code> (function calls). A &ldquo;method call&rdquo; simply chains
those together.</p><img src="image/classes/method.png" alt="The syntax tree for 'object.method(argument)" />
<p>That raises an interesting question. What happens when those two expressions are
pulled apart? Assuming that <code>method</code> in this example is a method on the class of
<code>object</code> and not a field on the instance, what should the following piece of
code do?</p>
<div class="codehilite"><pre><span class="k">var</span> <span class="i">m</span> = <span class="i">object</span>.<span class="i">method</span>;
<span class="i">m</span>(<span class="i">argument</span>);
</pre></div>
<p>This program &ldquo;looks up&rdquo; the method and stores the result<span class="em">&mdash;</span>whatever that is<span class="em">&mdash;</span>in a variable and then calls that object later. Is this allowed? Can you treat a
method like it&rsquo;s a function on the instance?</p>
<p>What about the other direction?</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Box</span> {}

<span class="k">fun</span> <span class="i">notMethod</span>(<span class="i">argument</span>) {
  <span class="k">print</span> <span class="s">&quot;called function with &quot;</span> + <span class="i">argument</span>;
}

<span class="k">var</span> <span class="i">box</span> = <span class="t">Box</span>();
<span class="i">box</span>.<span class="i">function</span> = <span class="i">notMethod</span>;
<span class="i">box</span>.<span class="i">function</span>(<span class="s">&quot;argument&quot;</span>);
</pre></div>
<p>This program creates an instance and then stores a function in a field on it.
Then it calls that function using the same syntax as a method call. Does that
work?</p>
<p>Different languages have different answers to these questions. One could write a
treatise on it. For Lox, we&rsquo;ll say the answer to both of these is yes, it does
work. We have a couple of reasons to justify that. For the second example<span class="em">&mdash;</span>calling a function stored in a field<span class="em">&mdash;</span>we want to support that because
first-class functions are useful and storing them in fields is a perfectly
normal thing to do.</p>
<p>The first example is more obscure. One motivation is that users generally expect
to be able to hoist a subexpression out into a local variable without changing
the meaning of the program. You can take this:</p>
<div class="codehilite"><pre><span class="i">breakfast</span>(<span class="i">omelette</span>.<span class="i">filledWith</span>(<span class="i">cheese</span>), <span class="i">sausage</span>);
</pre></div>
<p>And turn it into this:</p>
<div class="codehilite"><pre><span class="k">var</span> <span class="i">eggs</span> = <span class="i">omelette</span>.<span class="i">filledWith</span>(<span class="i">cheese</span>);
<span class="i">breakfast</span>(<span class="i">eggs</span>, <span class="i">sausage</span>);
</pre></div>
<p>And it does the same thing. Likewise, since the <code>.</code> and the <code>()</code> in a method
call <em>are</em> two separate expressions, it seems you should be able to hoist the
<em>lookup</em> part into a variable and then call it <span
name="callback">later</span>. We need to think carefully about what the <em>thing</em>
you get when you look up a method is, and how it behaves, even in weird cases
like:</p>
<aside name="callback">
<p>A motivating use for this is callbacks. Often, you want to pass a callback whose
body simply invokes a method on some object. Being able to look up the method and
pass it directly saves you the chore of manually declaring a function to wrap
it. Compare this:</p>
<div class="codehilite"><pre><span class="k">fun</span> <span class="i">callback</span>(<span class="i">a</span>, <span class="i">b</span>, <span class="i">c</span>) {
  <span class="i">object</span>.<span class="i">method</span>(<span class="i">a</span>, <span class="i">b</span>, <span class="i">c</span>);
}

<span class="i">takeCallback</span>(<span class="i">callback</span>);
</pre></div>
<p>With this:</p>
<div class="codehilite"><pre><span class="i">takeCallback</span>(<span class="i">object</span>.<span class="i">method</span>);
</pre></div>
</aside>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Person</span> {
  <span class="i">sayName</span>() {
    <span class="k">print</span> <span class="k">this</span>.<span class="i">name</span>;
  }
}

<span class="k">var</span> <span class="i">jane</span> = <span class="t">Person</span>();
<span class="i">jane</span>.<span class="i">name</span> = <span class="s">&quot;Jane&quot;</span>;

<span class="k">var</span> <span class="i">method</span> = <span class="i">jane</span>.<span class="i">sayName</span>;
<span class="i">method</span>(); <span class="c">// ?</span>
</pre></div>
<p>If you grab a handle to a method on some instance and call it later, does it
&ldquo;remember&rdquo; the instance it was pulled off from? Does <code>this</code> inside the method
still refer to that original object?</p>
<p>Here&rsquo;s a more pathological example to bend your brain:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Person</span> {
  <span class="i">sayName</span>() {
    <span class="k">print</span> <span class="k">this</span>.<span class="i">name</span>;
  }
}

<span class="k">var</span> <span class="i">jane</span> = <span class="t">Person</span>();
<span class="i">jane</span>.<span class="i">name</span> = <span class="s">&quot;Jane&quot;</span>;

<span class="k">var</span> <span class="i">bill</span> = <span class="t">Person</span>();
<span class="i">bill</span>.<span class="i">name</span> = <span class="s">&quot;Bill&quot;</span>;

<span class="i">bill</span>.<span class="i">sayName</span> = <span class="i">jane</span>.<span class="i">sayName</span>;
<span class="i">bill</span>.<span class="i">sayName</span>(); <span class="c">// ?</span>
</pre></div>
<p>Does that last line print &ldquo;Bill&rdquo; because that&rsquo;s the instance that we <em>called</em>
the method through, or &ldquo;Jane&rdquo; because it&rsquo;s the instance where we first grabbed
the method?</p>
<p>Equivalent code in Lua and JavaScript would print &ldquo;Bill&rdquo;. Those languages don&rsquo;t
really have a notion of &ldquo;methods&rdquo;. Everything is sort of functions-in-fields, so
it&rsquo;s not clear that <code>jane</code> &ldquo;owns&rdquo; <code>sayName</code> any more than <code>bill</code> does.</p>
<p>Lox, though, has real class syntax so we do know which callable things are
methods and which are functions. Thus, like Python, C#, and others, we will have
methods &ldquo;bind&rdquo; <code>this</code> to the original instance when the method is first grabbed.
Python calls <span name="bound">these</span> <strong>bound methods</strong>.</p>
<aside name="bound">
<p>I know, imaginative name, right?</p>
</aside>
<p>In practice, that&rsquo;s usually what you want. If you take a reference to a method
on some object so you can use it as a callback later, you want to remember the
instance it belonged to, even if that callback happens to be stored in a field
on some other object.</p>
<p>OK, that&rsquo;s a lot of semantics to load into your head. Forget about the edge
cases for a bit. We&rsquo;ll get back to those. For now, let&rsquo;s get basic method calls
working. We&rsquo;re already parsing the method declarations inside the class body, so
the next step is to resolve them.</p>
<div class="codehilite"><pre class="insert-before">    define(stmt.name);
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitClassStmt</em>()</div>
<pre class="insert">

    <span class="k">for</span> (<span class="t">Stmt</span>.<span class="t">Function</span> <span class="i">method</span> : <span class="i">stmt</span>.<span class="i">methods</span>) {
      <span class="t">FunctionType</span> <span class="i">declaration</span> = <span class="t">FunctionType</span>.<span class="i">METHOD</span>;
      <span class="i">resolveFunction</span>(<span class="i">method</span>, <span class="i">declaration</span>);<span name="local"> </span>
    }

</pre><pre class="insert-after">    return null;
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitClassStmt</em>()</div>

<aside name="local">
<p>Storing the function type in a local variable is pointless right now, but we&rsquo;ll
expand this code before too long and it will make more sense.</p>
</aside>
<p>We iterate through the methods in the class body and call the
<code>resolveFunction()</code> method we wrote for handling function declarations already.
The only difference is that we pass in a new FunctionType enum value.</p>
<div class="codehilite"><pre class="insert-before">    NONE,
</pre><pre class="insert-before">    <span class="i">FUNCTION</span><span class="insert-comma">,</span>
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in enum <em>FunctionType</em><br>
add <em>&ldquo;,&rdquo;</em> to previous line</div>
<pre class="insert">    <span class="i">METHOD</span>
</pre><pre class="insert-after">  }
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in enum <em>FunctionType</em>, add <em>&ldquo;,&rdquo;</em> to previous line</div>

<p>That&rsquo;s going to be important when we resolve <code>this</code> expressions. For now, don&rsquo;t
worry about it. The interesting stuff is in the interpreter.</p>
<div class="codehilite"><pre class="insert-before">    environment.define(stmt.name.lexeme, null);
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitClassStmt</em>()<br>
replace 1 line</div>
<pre class="insert">

    <span class="t">Map</span>&lt;<span class="t">String</span>, <span class="t">LoxFunction</span>&gt; <span class="i">methods</span> = <span class="k">new</span> <span class="t">HashMap</span>&lt;&gt;();
    <span class="k">for</span> (<span class="t">Stmt</span>.<span class="t">Function</span> <span class="i">method</span> : <span class="i">stmt</span>.<span class="i">methods</span>) {
      <span class="t">LoxFunction</span> <span class="i">function</span> = <span class="k">new</span> <span class="t">LoxFunction</span>(<span class="i">method</span>, <span class="i">environment</span>);
      <span class="i">methods</span>.<span class="i">put</span>(<span class="i">method</span>.<span class="i">name</span>.<span class="i">lexeme</span>, <span class="i">function</span>);
    }

    <span class="t">LoxClass</span> <span class="i">klass</span> = <span class="k">new</span> <span class="t">LoxClass</span>(<span class="i">stmt</span>.<span class="i">name</span>.<span class="i">lexeme</span>, <span class="i">methods</span>);
</pre><pre class="insert-after">    environment.assign(stmt.name, klass);
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitClassStmt</em>(), replace 1 line</div>

<p>When we interpret a class declaration statement, we turn the syntactic
representation of the class<span class="em">&mdash;</span>its AST node<span class="em">&mdash;</span>into its runtime representation.
Now, we need to do that for the methods contained in the class as well. Each
method declaration blossoms into a LoxFunction object.</p>
<p>We take all of those and wrap them up into a map, keyed by the method names.
That gets stored in LoxClass.</p>
<div class="codehilite"><pre class="insert-before">  final String name;
</pre><div class="source-file"><em>lox/LoxClass.java</em><br>
in class <em>LoxClass</em><br>
replace 4 lines</div>
<pre class="insert">  <span class="k">private</span> <span class="k">final</span> <span class="t">Map</span>&lt;<span class="t">String</span>, <span class="t">LoxFunction</span>&gt; <span class="i">methods</span>;

  <span class="t">LoxClass</span>(<span class="t">String</span> <span class="i">name</span>, <span class="t">Map</span>&lt;<span class="t">String</span>, <span class="t">LoxFunction</span>&gt; <span class="i">methods</span>) {
    <span class="k">this</span>.<span class="i">name</span> = <span class="i">name</span>;
    <span class="k">this</span>.<span class="i">methods</span> = <span class="i">methods</span>;
  }
</pre><pre class="insert-after">

  @Override
  public String toString() {
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, in class <em>LoxClass</em>, replace 4 lines</div>

<p>Where an instance stores state, the class stores behavior. LoxInstance has its
map of fields, and LoxClass gets a map of methods. Even though methods are
owned by the class, they are still accessed through instances of that class.</p>
<div class="codehilite"><pre class="insert-before">  Object get(Token name) {
    if (fields.containsKey(name.lexeme)) {
      return fields.get(name.lexeme);
    }

</pre><div class="source-file"><em>lox/LoxInstance.java</em><br>
in <em>get</em>()</div>
<pre class="insert">    <span class="t">LoxFunction</span> <span class="i">method</span> = <span class="i">klass</span>.<span class="i">findMethod</span>(<span class="i">name</span>.<span class="i">lexeme</span>);
    <span class="k">if</span> (<span class="i">method</span> != <span class="k">null</span>) <span class="k">return</span> <span class="i">method</span>;

</pre><pre class="insert-after">    throw new RuntimeError(name,<span name="hidden"> </span>
        &quot;Undefined property '&quot; + name.lexeme + &quot;'.&quot;);
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, in <em>get</em>()</div>

<p>When looking up a property on an instance, if we don&rsquo;t <span
name="shadow">find</span> a matching field, we look for a method with that name
on the instance&rsquo;s class. If found, we return that. This is where the distinction
between &ldquo;field&rdquo; and &ldquo;property&rdquo; becomes meaningful. When accessing a property,
you might get a field<span class="em">&mdash;</span>a bit of state stored on the instance<span class="em">&mdash;</span>or you could
hit a method defined on the instance&rsquo;s class.</p>
<p>The method is looked up using this:</p>
<aside name="shadow">
<p>Looking for a field first implies that fields shadow methods, a subtle but
important semantic point.</p>
</aside>
<div class="codehilite"><div class="source-file"><em>lox/LoxClass.java</em><br>
add after <em>LoxClass</em>()</div>
<pre>  <span class="t">LoxFunction</span> <span class="i">findMethod</span>(<span class="t">String</span> <span class="i">name</span>) {
    <span class="k">if</span> (<span class="i">methods</span>.<span class="i">containsKey</span>(<span class="i">name</span>)) {
      <span class="k">return</span> <span class="i">methods</span>.<span class="i">get</span>(<span class="i">name</span>);
    }

    <span class="k">return</span> <span class="k">null</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, add after <em>LoxClass</em>()</div>

<p>You can probably guess this method is going to get more interesting later. For
now, a simple map lookup on the class&rsquo;s method table is enough to get us
started. Give it a try:</p>
<p><span name="crunch"></span></p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Bacon</span> {
  <span class="i">eat</span>() {
    <span class="k">print</span> <span class="s">&quot;Crunch crunch crunch!&quot;</span>;
  }
}

<span class="t">Bacon</span>().<span class="i">eat</span>(); <span class="c">// Prints &quot;Crunch crunch crunch!&quot;.</span>
</pre></div>
<aside name="crunch">
<p>Apologies if you prefer chewy bacon over crunchy. Feel free to adjust the script
to your taste.</p>
</aside>
<h2><a href="#this" id="this"><small>12&#8202;.&#8202;6</small>This</a></h2>
<p>We can define both behavior and state on objects, but they aren&rsquo;t tied together
yet. Inside a method, we have no way to access the fields of the &ldquo;current&rdquo;
object<span class="em">&mdash;</span>the instance that the method was called on<span class="em">&mdash;</span>nor can we call other
methods on that same object.</p>
<p>To get at that instance, it needs a <span name="i">name</span>. Smalltalk,
Ruby, and Swift use &ldquo;self&rdquo;. Simula, C++, Java, and others use &ldquo;this&rdquo;. Python
uses &ldquo;self&rdquo; by convention, but you can technically call it whatever you like.</p>
<aside name="i">
<p>&ldquo;I&rdquo; would have been a great choice, but using &ldquo;i&rdquo; for loop variables predates
OOP and goes all the way back to Fortran. We are victims of the incidental
choices of our forebears.</p>
</aside>
<p>For Lox, since we generally hew to Java-ish style, we&rsquo;ll go with &ldquo;this&rdquo;. Inside
a method body, a <code>this</code> expression evaluates to the instance that the method was
called on. Or, more specifically, since methods are accessed and then invoked as
two steps, it will refer to the object that the method was <em>accessed</em> from.</p>
<p>That makes our job harder. Peep at:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Egotist</span> {
  <span class="i">speak</span>() {
    <span class="k">print</span> <span class="k">this</span>;
  }
}

<span class="k">var</span> <span class="i">method</span> = <span class="t">Egotist</span>().<span class="i">speak</span>;
<span class="i">method</span>();
</pre></div>
<p>On the second-to-last line, we grab a reference to the <code>speak()</code> method off an
instance of the class. That returns a function, and that function needs to
remember the instance it was pulled off of so that <em>later</em>, on the last line, it
can still find it when the function is called.</p>
<p>We need to take <code>this</code> at the point that the method is accessed and attach it to
the function somehow so that it stays around as long as we need it to. Hmm<span class="ellipse">&thinsp;.&thinsp;.&thinsp;.&nbsp;</span>a
way to store some extra data that hangs around a function, eh? That sounds an
awful lot like a <em>closure</em>, doesn&rsquo;t it?</p>
<p>If we defined <code>this</code> as a sort of hidden variable in an environment that
surrounds the function returned when looking up a method, then uses of <code>this</code> in
the body would be able to find it later. LoxFunction already has the ability to
hold on to a surrounding environment, so we have the machinery we need.</p>
<p>Let&rsquo;s walk through an example to see how it works:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Cake</span> {
  <span class="i">taste</span>() {
    <span class="k">var</span> <span class="i">adjective</span> = <span class="s">&quot;delicious&quot;</span>;
    <span class="k">print</span> <span class="s">&quot;The &quot;</span> + <span class="k">this</span>.<span class="i">flavor</span> + <span class="s">&quot; cake is &quot;</span> + <span class="i">adjective</span> + <span class="s">&quot;!&quot;</span>;
  }
}

<span class="k">var</span> <span class="i">cake</span> = <span class="t">Cake</span>();
<span class="i">cake</span>.<span class="i">flavor</span> = <span class="s">&quot;German chocolate&quot;</span>;
<span class="i">cake</span>.<span class="i">taste</span>(); <span class="c">// Prints &quot;The German chocolate cake is delicious!&quot;.</span>
</pre></div>
<p>When we first evaluate the class definition, we create a LoxFunction for
<code>taste()</code>. Its closure is the environment surrounding the class, in this case
the global one. So the LoxFunction we store in the class&rsquo;s method map looks
like so:</p><img src="image/classes/closure.png" alt="The initial closure for the method." />
<p>When we evaluate the <code>cake.taste</code> get expression, we create a new environment
that binds <code>this</code> to the object the method is accessed from (here, <code>cake</code>). Then
we make a <em>new</em> LoxFunction with the same code as the original one but using
that new environment as its closure.</p><img src="image/classes/bound-method.png" alt="The new closure that binds 'this'." />
<p>This is the LoxFunction that gets returned when evaluating the get expression
for the method name. When that function is later called by a <code>()</code> expression,
we create an environment for the method body as usual.</p><img src="image/classes/call.png" alt="Calling the bound method and creating a new environment for the method body." />
<p>The parent of the body environment is the environment we created earlier to bind
<code>this</code> to the current object. Thus any use of <code>this</code> inside the body
successfully resolves to that instance.</p>
<p>Reusing our environment code for implementing <code>this</code> also takes care of
interesting cases where methods and functions interact, like:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Thing</span> {
  <span class="i">getCallback</span>() {
    <span class="k">fun</span> <span class="i">localFunction</span>() {
      <span class="k">print</span> <span class="k">this</span>;
    }

    <span class="k">return</span> <span class="i">localFunction</span>;
  }
}

<span class="k">var</span> <span class="i">callback</span> = <span class="t">Thing</span>().<span class="i">getCallback</span>();
<span class="i">callback</span>();
</pre></div>
<p>In, say, JavaScript, it&rsquo;s common to return a callback from inside a method. That
callback may want to hang on to and retain access to the original object<span class="em">&mdash;</span>the
<code>this</code> value<span class="em">&mdash;</span>that the method was associated with. Our existing support for
closures and environment chains should do all this correctly.</p>
<p>Let&rsquo;s code it up. The first step is adding <span name="this-ast">new
syntax</span> for <code>this</code>.</p>
<div class="codehilite"><pre class="insert-before">      &quot;Set      : Expr object, Token name, Expr value&quot;,
</pre><div class="source-file"><em>tool/GenerateAst.java</em><br>
in <em>main</em>()</div>
<pre class="insert">      <span class="s">&quot;This     : Token keyword&quot;</span>,
</pre><pre class="insert-after">      &quot;Unary    : Token operator, Expr right&quot;,
</pre></div>
<div class="source-file-narrow"><em>tool/GenerateAst.java</em>, in <em>main</em>()</div>

<aside name="this-ast">
<p>The generated code for the new node is in <a href="appendix-ii.html#this-expression">Appendix II</a>.</p>
</aside>
<p>Parsing is simple since it&rsquo;s a single token which our lexer already
recognizes as a reserved word.</p>
<div class="codehilite"><pre class="insert-before">      return new Expr.Literal(previous().literal);
    }
</pre><div class="source-file"><em>lox/Parser.java</em><br>
in <em>primary</em>()</div>
<pre class="insert">

    <span class="k">if</span> (<span class="i">match</span>(<span class="i">THIS</span>)) <span class="k">return</span> <span class="k">new</span> <span class="t">Expr</span>.<span class="t">This</span>(<span class="i">previous</span>());
</pre><pre class="insert-after">

    if (match(IDENTIFIER)) {
</pre></div>
<div class="source-file-narrow"><em>lox/Parser.java</em>, in <em>primary</em>()</div>

<p>You can start to see how <code>this</code> works like a variable when we get to the
resolver.</p>
<div class="codehilite"><div class="source-file"><em>lox/Resolver.java</em><br>
add after <em>visitSetExpr</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Void</span> <span class="i">visitThisExpr</span>(<span class="t">Expr</span>.<span class="t">This</span> <span class="i">expr</span>) {
    <span class="i">resolveLocal</span>(<span class="i">expr</span>, <span class="i">expr</span>.<span class="i">keyword</span>);
    <span class="k">return</span> <span class="k">null</span>;
  }

</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, add after <em>visitSetExpr</em>()</div>

<p>We resolve it exactly like any other local variable using &ldquo;this&rdquo; as the name for
the &ldquo;variable&rdquo;. Of course, that&rsquo;s not going to work right now, because &ldquo;this&rdquo;
<em>isn&rsquo;t</em> declared in any scope. Let&rsquo;s fix that over in <code>visitClassStmt()</code>.</p>
<div class="codehilite"><pre class="insert-before">    define(stmt.name);

</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitClassStmt</em>()</div>
<pre class="insert">    <span class="i">beginScope</span>();
    <span class="i">scopes</span>.<span class="i">peek</span>().<span class="i">put</span>(<span class="s">&quot;this&quot;</span>, <span class="k">true</span>);

</pre><pre class="insert-after">    for (Stmt.Function method : stmt.methods) {
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitClassStmt</em>()</div>

<p>Before we step in and start resolving the method bodies, we push a new scope and
define &ldquo;this&rdquo; in it as if it were a variable. Then, when we&rsquo;re done, we discard
that surrounding scope.</p>
<div class="codehilite"><pre class="insert-before">    }

</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitClassStmt</em>()</div>
<pre class="insert">    <span class="i">endScope</span>();

</pre><pre class="insert-after">    return null;
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitClassStmt</em>()</div>

<p>Now, whenever a <code>this</code> expression is encountered (at least inside a method) it
will resolve to a &ldquo;local variable&rdquo; defined in an implicit scope just outside of
the block for the method body.</p>
<p>The resolver has a new <em>scope</em> for <code>this</code>, so the interpreter needs to create a
corresponding <em>environment</em> for it. Remember, we always have to keep the
resolver&rsquo;s scope chains and the interpreter&rsquo;s linked environments in sync with
each other. At runtime, we create the environment after we find the method on
the instance. We replace the previous line of code that simply returned the
method&rsquo;s LoxFunction with this:</p>
<div class="codehilite"><pre class="insert-before">    LoxFunction method = klass.findMethod(name.lexeme);
</pre><div class="source-file"><em>lox/LoxInstance.java</em><br>
in <em>get</em>()<br>
replace 1 line</div>
<pre class="insert">    <span class="k">if</span> (<span class="i">method</span> != <span class="k">null</span>) <span class="k">return</span> <span class="i">method</span>.<span class="i">bind</span>(<span class="k">this</span>);
</pre><pre class="insert-after">

    throw new RuntimeError(name,<span name="hidden"> </span>
        &quot;Undefined property '&quot; + name.lexeme + &quot;'.&quot;);
</pre></div>
<div class="source-file-narrow"><em>lox/LoxInstance.java</em>, in <em>get</em>(), replace 1 line</div>

<p>Note the new call to <code>bind()</code>. That looks like so:</p>
<div class="codehilite"><div class="source-file"><em>lox/LoxFunction.java</em><br>
add after <em>LoxFunction</em>()</div>
<pre>  <span class="t">LoxFunction</span> <span class="i">bind</span>(<span class="t">LoxInstance</span> <span class="i">instance</span>) {
    <span class="t">Environment</span> <span class="i">environment</span> = <span class="k">new</span> <span class="t">Environment</span>(<span class="i">closure</span>);
    <span class="i">environment</span>.<span class="i">define</span>(<span class="s">&quot;this&quot;</span>, <span class="i">instance</span>);
    <span class="k">return</span> <span class="k">new</span> <span class="t">LoxFunction</span>(<span class="i">declaration</span>, <span class="i">environment</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/LoxFunction.java</em>, add after <em>LoxFunction</em>()</div>

<p>There isn&rsquo;t much to it. We create a new environment nestled inside the method&rsquo;s
original closure. Sort of a closure-within-a-closure. When the method is called,
that will become the parent of the method body&rsquo;s environment.</p>
<p>We declare &ldquo;this&rdquo; as a variable in that environment and bind it to the given
instance, the instance that the method is being accessed from. <em>Et voilà</em>, the
returned LoxFunction now carries around its own little persistent world where
&ldquo;this&rdquo; is bound to the object.</p>
<p>The remaining task is interpreting those <code>this</code> expressions. Similar to the
resolver, it is the same as interpreting a variable expression.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitSetExpr</em>()</div>
<pre>  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Object</span> <span class="i">visitThisExpr</span>(<span class="t">Expr</span>.<span class="t">This</span> <span class="i">expr</span>) {
    <span class="k">return</span> <span class="i">lookUpVariable</span>(<span class="i">expr</span>.<span class="i">keyword</span>, <span class="i">expr</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitSetExpr</em>()</div>

<p>Go ahead and give it a try using that cake example from earlier. With less than
twenty lines of code, our interpreter handles <code>this</code> inside methods even in all
of the weird ways it can interact with nested classes, functions inside methods,
handles to methods, etc.</p>
<h3><a href="#invalid-uses-of-this" id="invalid-uses-of-this"><small>12&#8202;.&#8202;6&#8202;.&#8202;1</small>Invalid uses of this</a></h3>
<p>Wait a minute. What happens if you try to use <code>this</code> <em>outside</em> of a method? What
about:</p>
<div class="codehilite"><pre><span class="k">print</span> <span class="k">this</span>;
</pre></div>
<p>Or:</p>
<div class="codehilite"><pre><span class="k">fun</span> <span class="i">notAMethod</span>() {
  <span class="k">print</span> <span class="k">this</span>;
}
</pre></div>
<p>There is no instance for <code>this</code> to point to if you&rsquo;re not in a method. We could
give it some default value like <code>nil</code> or make it a runtime error, but the user
has clearly made a mistake. The sooner they find and fix that mistake, the
happier they&rsquo;ll be.</p>
<p>Our resolution pass is a fine place to detect this error statically. It already
detects <code>return</code> statements outside of functions. We&rsquo;ll do something similar for
<code>this</code>. In the vein of our existing FunctionType enum, we define a new ClassType
one.</p>
<div class="codehilite"><pre class="insert-before">  }
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
add after enum <em>FunctionType</em></div>
<pre class="insert">

  <span class="k">private</span> <span class="k">enum</span> <span class="t">ClassType</span> {
    <span class="i">NONE</span>,
    <span class="i">CLASS</span>
  }

  <span class="k">private</span> <span class="t">ClassType</span> <span class="i">currentClass</span> = <span class="t">ClassType</span>.<span class="i">NONE</span>;

</pre><pre class="insert-after">  void resolve(List&lt;Stmt&gt; statements) {
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, add after enum <em>FunctionType</em></div>

<p>Yes, it could be a Boolean. When we get to inheritance, it will get a third
value, hence the enum right now. We also add a corresponding field,
<code>currentClass</code>. Its value tells us if we are currently inside a class
declaration while traversing the syntax tree. It starts out <code>NONE</code> which means
we aren&rsquo;t in one.</p>
<p>When we begin to resolve a class declaration, we change that.</p>
<div class="codehilite"><pre class="insert-before">  public Void visitClassStmt(Stmt.Class stmt) {
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitClassStmt</em>()</div>
<pre class="insert">    <span class="t">ClassType</span> <span class="i">enclosingClass</span> = <span class="i">currentClass</span>;
    <span class="i">currentClass</span> = <span class="t">ClassType</span>.<span class="i">CLASS</span>;

</pre><pre class="insert-after">    declare(stmt.name);
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitClassStmt</em>()</div>

<p>As with <code>currentFunction</code>, we store the previous value of the field in a local
variable. This lets us piggyback onto the JVM to keep a stack of <code>currentClass</code>
values. That way we don&rsquo;t lose track of the previous value if one class nests
inside another.</p>
<p>Once the methods have been resolved, we &ldquo;pop&rdquo; that stack by restoring the old
value.</p>
<div class="codehilite"><pre class="insert-before">    endScope();

</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitClassStmt</em>()</div>
<pre class="insert">    <span class="i">currentClass</span> = <span class="i">enclosingClass</span>;
</pre><pre class="insert-after">    return null;
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitClassStmt</em>()</div>

<p>When we resolve a <code>this</code> expression, the <code>currentClass</code> field gives us the bit
of data we need to report an error if the expression doesn&rsquo;t occur nestled
inside a method body.</p>
<div class="codehilite"><pre class="insert-before">  public Void visitThisExpr(Expr.This expr) {
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitThisExpr</em>()</div>
<pre class="insert">    <span class="k">if</span> (<span class="i">currentClass</span> == <span class="t">ClassType</span>.<span class="i">NONE</span>) {
      <span class="t">Lox</span>.<span class="i">error</span>(<span class="i">expr</span>.<span class="i">keyword</span>,
          <span class="s">&quot;Can&#39;t use &#39;this&#39; outside of a class.&quot;</span>);
      <span class="k">return</span> <span class="k">null</span>;
    }

</pre><pre class="insert-after">    resolveLocal(expr, expr.keyword);
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitThisExpr</em>()</div>

<p>That should help users use <code>this</code> correctly, and it saves us from having to
handle misuse at runtime in the interpreter.</p>
<h2><a href="#constructors-and-initializers" id="constructors-and-initializers"><small>12&#8202;.&#8202;7</small>Constructors and Initializers</a></h2>
<p>We can do almost everything with classes now, and as we near the end of the
chapter we find ourselves strangely focused on a beginning. Methods and fields
let us encapsulate state and behavior together so that an object always <em>stays</em>
in a valid configuration. But how do we ensure a brand new object <em>starts</em> in a
good state?</p>
<p>For that, we need constructors. I find them one of the trickiest parts of a
language to design, and if you peer closely at most other languages, you&rsquo;ll see
<span name="cracks">cracks</span> around object construction where the seams of
the design don&rsquo;t quite fit together perfectly. Maybe there&rsquo;s something
intrinsically messy about the moment of birth.</p>
<aside name="cracks">
<p>A few examples: In Java, even though final fields must be initialized, it is
still possible to read one <em>before</em> it has been. Exceptions<span class="em">&mdash;</span>a huge, complex
feature<span class="em">&mdash;</span>were added to C++ mainly as a way to emit errors from constructors.</p>
</aside>
<p>&ldquo;Constructing&rdquo; an object is actually a pair of operations:</p>
<ol>
<li>
<p>The runtime <span name="allocate"><em>allocates</em></span> the memory required for
a fresh instance. In most languages, this operation is at a fundamental
level beneath what user code is able to access.</p>
<aside name="allocate">
<p>C++&rsquo;s &ldquo;<a href="https://en.wikipedia.org/wiki/Placement_syntax">placement new</a>&rdquo; is a rare example where the bowels of allocation
are laid bare for the programmer to prod.</p>
</aside></li>
<li>
<p>Then, a user-provided chunk of code is called which <em>initializes</em> the
unformed object.</p>
</li>
</ol>
<p>The latter is what we tend to think of when we hear &ldquo;constructor&rdquo;, but the
language itself has usually done some groundwork for us before we get to that
point. In fact, our Lox interpreter already has that covered when it creates a
new LoxInstance object.</p>
<p>We&rsquo;ll do the remaining part<span class="em">&mdash;</span>user-defined initialization<span class="em">&mdash;</span>now. Languages
have a variety of notations for the chunk of code that sets up a new object for
a class. C++, Java, and C# use a method whose name matches the class name. Ruby
and Python call it <code>init()</code>. The latter is nice and short, so we&rsquo;ll do that.</p>
<p>In LoxClass&rsquo;s implementation of LoxCallable, we add a few more lines.</p>
<div class="codehilite"><pre class="insert-before">                     List&lt;Object&gt; arguments) {
    LoxInstance instance = new LoxInstance(this);
</pre><div class="source-file"><em>lox/LoxClass.java</em><br>
in <em>call</em>()</div>
<pre class="insert">    <span class="t">LoxFunction</span> <span class="i">initializer</span> = <span class="i">findMethod</span>(<span class="s">&quot;init&quot;</span>);
    <span class="k">if</span> (<span class="i">initializer</span> != <span class="k">null</span>) {
      <span class="i">initializer</span>.<span class="i">bind</span>(<span class="i">instance</span>).<span class="i">call</span>(<span class="i">interpreter</span>, <span class="i">arguments</span>);
    }

</pre><pre class="insert-after">    return instance;
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, in <em>call</em>()</div>

<p>When a class is called, after the LoxInstance is created, we look for an &ldquo;init&rdquo;
method. If we find one, we immediately bind and invoke it just like a normal
method call. The argument list is forwarded along.</p>
<p>That argument list means we also need to tweak how a class declares its arity.</p>
<div class="codehilite"><pre class="insert-before">  public int arity() {
</pre><div class="source-file"><em>lox/LoxClass.java</em><br>
in <em>arity</em>()<br>
replace 1 line</div>
<pre class="insert">    <span class="t">LoxFunction</span> <span class="i">initializer</span> = <span class="i">findMethod</span>(<span class="s">&quot;init&quot;</span>);
    <span class="k">if</span> (<span class="i">initializer</span> == <span class="k">null</span>) <span class="k">return</span> <span class="n">0</span>;
    <span class="k">return</span> <span class="i">initializer</span>.<span class="i">arity</span>();
</pre><pre class="insert-after">  }
</pre></div>
<div class="source-file-narrow"><em>lox/LoxClass.java</em>, in <em>arity</em>(), replace 1 line</div>

<p>If there is an initializer, that method&rsquo;s arity determines how many arguments
you must pass when you call the class itself. We don&rsquo;t <em>require</em> a class to
define an initializer, though, as a convenience. If you don&rsquo;t have an
initializer, the arity is still zero.</p>
<p>That&rsquo;s basically it. Since we bind the <code>init()</code> method before we call it, it has
access to <code>this</code> inside its body. That, along with the arguments passed to the
class, are all you need to be able to set up the new instance however you
desire.</p>
<h3><a href="#invoking-init-directly" id="invoking-init-directly"><small>12&#8202;.&#8202;7&#8202;.&#8202;1</small>Invoking init() directly</a></h3>
<p>As usual, exploring this new semantic territory rustles up a few weird
creatures. Consider:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Foo</span> {
  <span class="i">init</span>() {
    <span class="k">print</span> <span class="k">this</span>;
  }
}

<span class="k">var</span> <span class="i">foo</span> = <span class="t">Foo</span>();
<span class="k">print</span> <span class="i">foo</span>.<span class="i">init</span>();
</pre></div>
<p>Can you &ldquo;re-initialize&rdquo; an object by directly calling its <code>init()</code> method? If
you do, what does it return? A <span name="compromise">reasonable</span> answer
would be <code>nil</code> since that&rsquo;s what it appears the body returns.</p>
<p>However<span class="em">&mdash;</span>and I generally dislike compromising to satisfy the
implementation<span class="em">&mdash;</span>it will make clox&rsquo;s implementation of constructors much
easier if we say that <code>init()</code> methods always return <code>this</code>, even when
directly called. In order to keep jlox compatible with that, we add a little
special case code in LoxFunction.</p>
<aside name="compromise">
<p>Maybe &ldquo;dislike&rdquo; is too strong a claim. It&rsquo;s reasonable to have the constraints
and resources of your implementation affect the design of the language. There
are only so many hours in the day, and if a cut corner here or there lets you get
more features to users in less time, it may very well be a net win for their
happiness and productivity. The trick is figuring out <em>which</em> corners to cut
that won&rsquo;t cause your users and future self to curse your shortsightedness.</p>
</aside>
<div class="codehilite"><pre class="insert-before">      return returnValue.value;
    }
</pre><div class="source-file"><em>lox/LoxFunction.java</em><br>
in <em>call</em>()</div>
<pre class="insert">

    <span class="k">if</span> (<span class="i">isInitializer</span>) <span class="k">return</span> <span class="i">closure</span>.<span class="i">getAt</span>(<span class="n">0</span>, <span class="s">&quot;this&quot;</span>);
</pre><pre class="insert-after">    return null;
</pre></div>
<div class="source-file-narrow"><em>lox/LoxFunction.java</em>, in <em>call</em>()</div>

<p>If the function is an initializer, we override the actual return value and
forcibly return <code>this</code>. That relies on a new <code>isInitializer</code> field.</p>
<div class="codehilite"><pre class="insert-before">  private final Environment closure;

</pre><div class="source-file"><em>lox/LoxFunction.java</em><br>
in class <em>LoxFunction</em><br>
replace 1 line</div>
<pre class="insert">  <span class="k">private</span> <span class="k">final</span> <span class="t">boolean</span> <span class="i">isInitializer</span>;

  <span class="t">LoxFunction</span>(<span class="t">Stmt</span>.<span class="t">Function</span> <span class="i">declaration</span>, <span class="t">Environment</span> <span class="i">closure</span>,
              <span class="t">boolean</span> <span class="i">isInitializer</span>) {
    <span class="k">this</span>.<span class="i">isInitializer</span> = <span class="i">isInitializer</span>;
</pre><pre class="insert-after">    this.closure = closure;
    this.declaration = declaration;
</pre></div>
<div class="source-file-narrow"><em>lox/LoxFunction.java</em>, in class <em>LoxFunction</em>, replace 1 line</div>

<p>We can&rsquo;t simply see if the name of the LoxFunction is &ldquo;init&rdquo; because the user
could have defined a <em>function</em> with that name. In that case, there <em>is</em> no
<code>this</code> to return. To avoid <em>that</em> weird edge case, we&rsquo;ll directly store whether
the LoxFunction represents an initializer method. That means we need to go back
and fix the few places where we create LoxFunctions.</p>
<div class="codehilite"><pre class="insert-before">  public Void visitFunctionStmt(Stmt.Function stmt) {
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitFunctionStmt</em>()<br>
replace 1 line</div>
<pre class="insert">    <span class="t">LoxFunction</span> <span class="i">function</span> = <span class="k">new</span> <span class="t">LoxFunction</span>(<span class="i">stmt</span>, <span class="i">environment</span>,
                                           <span class="k">false</span>);
</pre><pre class="insert-after">    environment.define(stmt.name.lexeme, function);
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitFunctionStmt</em>(), replace 1 line</div>

<p>For actual function declarations, <code>isInitializer</code> is always false. For methods,
we check the name.</p>
<div class="codehilite"><pre class="insert-before">    for (Stmt.Function method : stmt.methods) {
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitClassStmt</em>()<br>
replace 1 line</div>
<pre class="insert">      <span class="t">LoxFunction</span> <span class="i">function</span> = <span class="k">new</span> <span class="t">LoxFunction</span>(<span class="i">method</span>, <span class="i">environment</span>,
          <span class="i">method</span>.<span class="i">name</span>.<span class="i">lexeme</span>.<span class="i">equals</span>(<span class="s">&quot;init&quot;</span>));
</pre><pre class="insert-after">      methods.put(method.name.lexeme, function);
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitClassStmt</em>(), replace 1 line</div>

<p>And then in <code>bind()</code> where we create the closure that binds <code>this</code> to a method,
we pass along the original method&rsquo;s value.</p>
<div class="codehilite"><pre class="insert-before">    environment.define(&quot;this&quot;, instance);
</pre><div class="source-file"><em>lox/LoxFunction.java</em><br>
in <em>bind</em>()<br>
replace 1 line</div>
<pre class="insert">    <span class="k">return</span> <span class="k">new</span> <span class="t">LoxFunction</span>(<span class="i">declaration</span>, <span class="i">environment</span>,
                           <span class="i">isInitializer</span>);
</pre><pre class="insert-after">  }
</pre></div>
<div class="source-file-narrow"><em>lox/LoxFunction.java</em>, in <em>bind</em>(), replace 1 line</div>

<h3><a href="#returning-from-init" id="returning-from-init"><small>12&#8202;.&#8202;7&#8202;.&#8202;2</small>Returning from init()</a></h3>
<p>We aren&rsquo;t out of the woods yet. We&rsquo;ve been assuming that a user-written
initializer doesn&rsquo;t explicitly return a value because most constructors don&rsquo;t.
What should happen if a user tries:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Foo</span> {
  <span class="i">init</span>() {
    <span class="k">return</span> <span class="s">&quot;something else&quot;</span>;
  }
}
</pre></div>
<p>It&rsquo;s definitely not going to do what they want, so we may as well make it a
static error. Back in the resolver, we add another case to FunctionType.</p>
<div class="codehilite"><pre class="insert-before">    FUNCTION,
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in enum <em>FunctionType</em></div>
<pre class="insert">    <span class="i">INITIALIZER</span>,
</pre><pre class="insert-after">    METHOD
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in enum <em>FunctionType</em></div>

<p>We use the visited method&rsquo;s name to determine if we&rsquo;re resolving an initializer
or not.</p>
<div class="codehilite"><pre class="insert-before">      FunctionType declaration = FunctionType.METHOD;
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitClassStmt</em>()</div>
<pre class="insert">      <span class="k">if</span> (<span class="i">method</span>.<span class="i">name</span>.<span class="i">lexeme</span>.<span class="i">equals</span>(<span class="s">&quot;init&quot;</span>)) {
        <span class="i">declaration</span> = <span class="t">FunctionType</span>.<span class="i">INITIALIZER</span>;
      }

</pre><pre class="insert-after">      resolveFunction(method, declaration);<span name="local"> </span>
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitClassStmt</em>()</div>

<p>When we later traverse into a <code>return</code> statement, we check that field and make
it an error to return a value from inside an <code>init()</code> method.</p>
<div class="codehilite"><pre class="insert-before">    if (stmt.value != null) {
</pre><div class="source-file"><em>lox/Resolver.java</em><br>
in <em>visitReturnStmt</em>()</div>
<pre class="insert">      <span class="k">if</span> (<span class="i">currentFunction</span> == <span class="t">FunctionType</span>.<span class="i">INITIALIZER</span>) {
        <span class="t">Lox</span>.<span class="i">error</span>(<span class="i">stmt</span>.<span class="i">keyword</span>,
            <span class="s">&quot;Can&#39;t return a value from an initializer.&quot;</span>);
      }

</pre><pre class="insert-after">      resolve(stmt.value);
</pre></div>
<div class="source-file-narrow"><em>lox/Resolver.java</em>, in <em>visitReturnStmt</em>()</div>

<p>We&rsquo;re <em>still</em> not done. We statically disallow returning a <em>value</em> from an
initializer, but you can still use an empty early <code>return</code>.</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Foo</span> {
  <span class="i">init</span>() {
    <span class="k">return</span>;
  }
}
</pre></div>
<p>That is actually kind of useful sometimes, so we don&rsquo;t want to disallow it
entirely. Instead, it should return <code>this</code> instead of <code>nil</code>. That&rsquo;s an easy fix
over in LoxFunction.</p>
<div class="codehilite"><pre class="insert-before">    } catch (Return returnValue) {
</pre><div class="source-file"><em>lox/LoxFunction.java</em><br>
in <em>call</em>()</div>
<pre class="insert">      <span class="k">if</span> (<span class="i">isInitializer</span>) <span class="k">return</span> <span class="i">closure</span>.<span class="i">getAt</span>(<span class="n">0</span>, <span class="s">&quot;this&quot;</span>);

</pre><pre class="insert-after">      return returnValue.value;
</pre></div>
<div class="source-file-narrow"><em>lox/LoxFunction.java</em>, in <em>call</em>()</div>

<p>If we&rsquo;re in an initializer and execute a <code>return</code> statement, instead of
returning the value (which will always be <code>nil</code>), we again return <code>this</code>.</p>
<p>Phew! That was a whole list of tasks but our reward is that our little
interpreter has grown an entire programming paradigm. Classes, methods, fields,
<code>this</code>, and constructors. Our baby language is looking awfully grown-up.</p>
<div class="challenges">
<h2><a href="#challenges" id="challenges">Challenges</a></h2>
<ol>
<li>
<p>We have methods on instances, but there is no way to define &ldquo;static&rdquo; methods
that can be called directly on the class object itself. Add support for
them. Use a <code>class</code> keyword preceding the method to indicate a static method
that hangs off the class object.</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Math</span> {
  <span class="k">class</span> <span class="i">square</span>(<span class="i">n</span>) {
    <span class="k">return</span> <span class="i">n</span> * <span class="i">n</span>;
  }
}

<span class="k">print</span> <span class="t">Math</span>.<span class="i">square</span>(<span class="n">3</span>); <span class="c">// Prints &quot;9&quot;.</span>
</pre></div>
<p>You can solve this however you like, but the &ldquo;<a href="https://en.wikipedia.org/wiki/Metaclass">metaclasses</a>&rdquo; used by
Smalltalk and Ruby are a particularly elegant approach. <em>Hint: Make LoxClass
extend LoxInstance and go from there.</em></p>
</li>
<li>
<p>Most modern languages support &ldquo;getters&rdquo; and &ldquo;setters&rdquo;<span class="em">&mdash;</span>members on a class
that look like field reads and writes but that actually execute user-defined
code. Extend Lox to support getter methods. These are declared without a
parameter list. The body of the getter is executed when a property with that
name is accessed.</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="t">Circle</span> {
  <span class="i">init</span>(<span class="i">radius</span>) {
    <span class="k">this</span>.<span class="i">radius</span> = <span class="i">radius</span>;
  }

  <span class="i">area</span> {
    <span class="k">return</span> <span class="n">3.141592653</span> * <span class="k">this</span>.<span class="i">radius</span> * <span class="k">this</span>.<span class="i">radius</span>;
  }
}

<span class="k">var</span> <span class="i">circle</span> = <span class="t">Circle</span>(<span class="n">4</span>);
<span class="k">print</span> <span class="i">circle</span>.<span class="i">area</span>; <span class="c">// Prints roughly &quot;50.2655&quot;.</span>
</pre></div>
</li>
<li>
<p>Python and JavaScript allow you to freely access an object&rsquo;s fields from
outside of its own methods. Ruby and Smalltalk encapsulate instance state.
Only methods on the class can access the raw fields, and it is up to the
class to decide which state is exposed. Most statically typed languages
offer modifiers like <code>private</code> and <code>public</code> to control which parts of a
class are externally accessible on a per-member basis.</p>
<p>What are the trade-offs between these approaches and why might a language
prefer one or the other?</p>
</li>
</ol>
</div>
<div class="design-note">
<h2><a href="#design-note" id="design-note">Design Note: Prototypes and Power</a></h2>
<p>In this chapter, we introduced two new runtime entities, LoxClass and
LoxInstance. The former is where behavior for objects lives, and the latter is
for state. What if you could define methods right on a single object, inside
LoxInstance? In that case, we wouldn&rsquo;t need LoxClass at all. LoxInstance would
be a complete package for defining the behavior and state of an object.</p>
<p>We&rsquo;d still want some way, without classes, to reuse behavior across multiple
instances. We could let a LoxInstance <a href="https://en.wikipedia.org/wiki/Prototype-based_programming#Delegation"><em>delegate</em></a> directly to another
LoxInstance to reuse its fields and methods, sort of like inheritance.</p>
<p>Users would model their program as a constellation of objects, some of which
delegate to each other to reflect commonality. Objects used as delegates
represent &ldquo;canonical&rdquo; or &ldquo;prototypical&rdquo; objects that others refine. The result
is a simpler runtime with only a single internal construct, LoxInstance.</p>
<p>That&rsquo;s where the name <strong><a href="https://en.wikipedia.org/wiki/Prototype-based_programming">prototypes</a></strong> comes from for this paradigm. It
was invented by David Ungar and Randall Smith in a language called <a href="http://www.selflanguage.org/">Self</a>.
They came up with it by starting with Smalltalk and following the above mental
exercise to see how much they could pare it down.</p>
<p>Prototypes were an academic curiosity for a long time, a fascinating one that
generated interesting research but didn&rsquo;t make a dent in the larger world of
programming. That is, until Brendan Eich crammed prototypes into JavaScript,
which then promptly took over the world. Many (many) <span
name="words">words</span> have been written about prototypes in JavaScript.
Whether that shows that prototypes are brilliant or confusing<span class="em">&mdash;</span>or both!<span class="em">&mdash;</span>is
an open question.</p>
<aside name="words">
<p>Including <a href="http://gameprogrammingpatterns.com/prototype.html">more than a handful</a> by yours truly.</p>
</aside>
<p>I won&rsquo;t get into whether or not I think prototypes are a good idea for a
language. I&rsquo;ve made languages that are <a href="http://finch.stuffwithstuff.com/">prototypal</a> and
<a href="http://wren.io/">class-based</a>, and my opinions of both are complex. What I want to discuss
is the role of <em>simplicity</em> in a language.</p>
<p>Prototypes are simpler than classes<span class="em">&mdash;</span>less code for the language implementer to
write, and fewer concepts for the user to learn and understand. Does that make
them better? We language nerds have a tendency to fetishize minimalism.
Personally, I think simplicity is only part of the equation. What we really want
to give the user is <em>power</em>, which I define as:</p>
<div class="codehilite"><pre>power = breadth × ease ÷ complexity
</pre></div>
<p>None of these are precise numeric measures. I&rsquo;m using math as analogy here, not
actual quantification.</p>
<ul>
<li>
<p><strong>Breadth</strong> is the range of different things the language lets you express.
C has a lot of breadth<span class="em">&mdash;</span>it&rsquo;s been used for everything from operating
systems to user applications to games. Domain-specific languages like
AppleScript and Matlab have less breadth.</p>
</li>
<li>
<p><strong>Ease</strong> is how little effort it takes to make the language do what you
want. &ldquo;Usability&rdquo; might be another term, though it carries more baggage than
I want to bring in. &ldquo;Higher-level&rdquo; languages tend to have more ease than
&ldquo;lower-level&rdquo; ones. Most languages have a &ldquo;grain&rdquo; to them where some things
feel easier to express than others.</p>
</li>
<li>
<p><strong>Complexity</strong> is how big the language (including its runtime, core libraries,
tools, ecosystem, etc.) is. People talk about how many pages are in a
language&rsquo;s spec, or how many keywords it has. It&rsquo;s how much the user has to
load into their wetware before they can be productive in the system. It is
the antonym of simplicity.</p>
</li>
</ul>
<p>Reducing complexity <em>does</em> increase power. The smaller the denominator, the
larger the resulting value, so our intuition that simplicity is good is valid.
However, when reducing complexity, we must take care not to sacrifice breadth or
ease in the process, or the total power may go down. Java would be a strictly
<em>simpler</em> language if it removed strings, but it probably wouldn&rsquo;t handle text
manipulation tasks well, nor would it be as easy to get things done.</p>
<p>The art, then, is finding <em>accidental</em> complexity that can be omitted<span class="em">&mdash;</span>language features and interactions that don&rsquo;t carry their weight by increasing
the breadth or ease of using the language.</p>
<p>If users want to express their program in terms of categories of objects, then
baking classes into the language increases the ease of doing that, hopefully by
a large enough margin to pay for the added complexity. But if that isn&rsquo;t how
users are using your language, then by all means leave classes out.</p>
</div>

<footer>
<a href="inheritance.html" class="next">
  Next Chapter: &ldquo;Inheritance&rdquo; &rarr;
</a>
Handcrafted by Robert Nystrom&ensp;&mdash;&ensp;<a href="https://github.com/munificent/craftinginterpreters/blob/master/LICENSE" target="_blank">&copy; 2015&hairsp;&ndash;&hairsp;2021</a>
</footer>
</article>

</div>
</body>
</html>
